
var pageInitObj = {
	initPage : function() {
		$(document).ajaxStart(function() {
			$('#ajaxIndicatorOn').fadeIn(500)
		}).ajaxStop(function(){
			$('#ajaxIndicatorOn').fadeOut(3000);
		}).ajaxComplete(function(event,request,settings){
			if (request.status == '403') {
				window.location = siteURL+'login/index/expired';
			}
		});

        $.ajaxSetup({
            cache : false
        });

        genericFunctions.checkboxTrigger();
        genericFunctions.prepTogglePanels();

        contactObj.makeContactLinks();
        
        /*
         * Activate main menu drop-downs
         */
        $("#navmenu-h li").hover(
            function() {
                $(this).addClass("iehover");
            },
            function() {
                $(this).removeClass("iehover");
            }
        );
    
	    /*
	     * Initialize notification system
	     */
		$("#popupGrowlWindow").notify({
			speed: 500,
			expires: 5000
		});		
	    
	    /*
	     * Initialize message system
	     */
	    if ($('#pageLeftColumn').attr('pageID') == 'clientDashboard') {
	    	var sendTo   = 'individual';	
	    	var sendToID = $('#accountUserid').val();
	    	var from     = $('#clientID').val();
	    	var fromType = 'client';
            var toClient = false;
            var clientID = '';
	    } else {
	    	var sendTo = eval(teamMembers);
	    	var sendToID = '';
	    	var from     = numbers[0];
	    	var fromType = 'owner';
            var toClient = true;
            var clientID = $('#clientID').val();
	    }
	    $('body').makeMessageBox({
              elementClass: 'messageBoxContainerLink',
              link:         true,
              sendTo:       sendTo,
              sendToID:     sendToID,
              fromID:       from,
              fromType:     fromType,
              fileAttach:   true,
              toClient:     toClient,
              clientID:     clientID

        });        

        /*
         * Initialize trash notification system
         */
        trashHelperObj.initTrash();

		/*
		 * Initialize mail window
		 */
		$('#buttonSiteMail').click(function() {
			$('.widgetContentContainer').hide();
            $('#messageContent').show();
			$('#bigModalBody > #messageContent').html(messageData);
            $('#bigModalHeaderTitleContainer').html(commonTerms['messages']);
			$('#bigModalBody > #messageContent').alternateContainerRowColors();

            $('.markMessageRead').click(function() {
                var messageID = $(this).attr('messageID');
                var messageContainer = $(this).parents('div.messageContainer');
                var numberOfMessages = parseInt($('#buttonSiteMail span').html());
                $.getJSON(siteURL+'messaging/Messages/markMessageRead/'+messageID, function(payload) {
                    messageContainer.fadeOut('fast');
                    $('#buttonSiteMail span').html(parseInt(numberOfMessages-1));
                });
            });

			$('#bigModal').show();
		});
		
		$('.bigModalClose').click(function() {
			$('#bigModal').hide();
		});
		    
	    /*
	     * Activate header button messages
	     * (litte round buttons on the right)
	     */
	    $('.headerButton').hover(
	    	function() {
	    		$('#headerControlsMessage').html($(this).attr('title'));
			}, function() {
				$('#headerControlsMessage').html('');
	  	});       
	  	
	  	/*
	  	 * Initialize context help system
	  	 */
	  	 helpObj.contextHelp();
	  	
	  	/*
	  	 * Initialize form stuff
	  	 */
	  	 formObj.initForm();
	  	
	    /*
         * Initialize message polling system
         */
         setInterval("getMessageObj.pollMessages()",300000);

        /*
         * Let's poll on page load
         */
         getMessageObj.pollMessages();
        
        /*
         * Initialize print buttons
         */
         printObj.initPrint();

        /*
         * Initialize site search
         */
         siteSearchObj.initSearchBox();
        
        /*
         * Initialize file upload buttons and modal window
         */
		 fileManagerObj.fileManagerButton();

		 /*
		  * Initialize pop-up menus
		  */
		 pageInitObj.popUpMenus();

         /*
		  * Initialize feed popup windows
		  */
		 pageInitObj.feedPopups();

		 if ($('#pageOneColumn').attr('pageID') != 'dashboard') {
			pageInitObj.footerWidgets();
		 } else {
			$('#footerWidgets').hide();
		 }

		 /*
		  * Initialize settings links
		  */
		 settingsObj.settingLinkInit();

         /*
          * Initialize bug logging
          */
         bugReportObj.attachEventHandlers();

         /*
          * Initialize language selector
          */
         languageObj.initLanguageSelect();

		 /*
		  * Initialize SWF Upload
		  */
         if (numbers[2] > 0) {
            filesObj.attachUploadEventHandlers();
         }

         /*
          * Initialize some modal dialog boxes
          */
         $('#modalDelete').dialog({
        	autoOpen:      false,
        	closeOnEscape: true,
        	height:        '300',
        	width:         '450px',
        	position:      'center',
            overlay: {
                background: '#000000',
                opacity: 0.8
            },
            draggable:     false,
            modal:         true,
			resizable:     false,
			zIndex:        1000,
			open:          function(event,ui) {
			}
        });

        $('#buttonDeleteModalCancel').click(function() {
           $('#modalDelete').dialog('close');
        });

        $('#modalAccountLimit').dialog({
        	autoOpen:      false,
        	closeOnEscape: true,
        	height:        '300',
        	width:         '400px',
        	position:      'center',
            draggable:     false,
            modal:         true,
			resizable:     false,
			zIndex:        1000,
			open:          function(event,ui) {
			}
        });

        $('#buttonAccountLimitModalClose').click(function() {
           $('#modalAccountLimit').dialog('close');
        });

        /*
         * Toggle page controls based on permissions
         */
        permissionsObj.renderControlsBasedOnPermissions();

        if ($('.scrollerHeadline').size()>1) {
            $('#cpoUpdateBar').contentScroller();
        } else {
            $('.scrollerHeadline').css('top','5px');
        }
        $('#closeFooterAlerts').click(function() {
           $.cookie('noCPOAlerts',Date.today().toString('yyyy-MM-dd'),{ expires: 100, path: '/'});
           $('#cpoUpdateBar').fadeOut('fast');

           return false;
        });
        /*
        if ($.cookie('noCPOAlerts') != '1') {
            $('#cpoUpdateBar').show();
            $('#cpoUpdateBar').contentScroller();

            $('#closeFooterAlerts').click(function() {
               $.cookie('noCPOAlerts',Date.today().toString('YYYY-MM-DD'),{ expires: 100, path: '/'});
               $('#cpoUpdateBar').fadeOut('fast');
               
               return false;
            });
        }
        */
	},
	footerWidgets : function() {
		/*
		 * This array will be generated by PHP from a session var on page load (includes/js.php)
		 */
		for(var a in footerWidgets) {
            if (footerWidgets[a] != null) {
                var widgetType = footerWidgets[a].WidgetName;
                var widgetName = footerWidgets[a].WName;
                $('#footerWidgetMenu').append('<li class="icon'+widgetType+' widgetFooter" title="'+widgetName+'" widgetType="'+widgetType+'"></li>');
            }
        }

		$('#footerWidgetMenu > li').click(function() {
            if ($(this).attr('widgetType') != 'filemanager') {
                pageInitObj.footerWidgetClick($(this));
            }
		});
	},
	footerWidgetClick : function(widgetObj) {
		$('.widgetContentContainer').hide();
		var widgetType = $(widgetObj).attr('widgetType');
        var widgetUser = $(widgetObj).attr('widgetUser');
		var loadVar = eval('widgetLoaded_'+widgetType);

		$('#widgetContent_'+widgetType).show();
		$('#bigModalHeaderTitleContainer').html($(widgetObj).attr('title'));
		if (loadVar == false) {
			widgetLoaderObj.loadWidgetContent(widgetType,widgetUser);
		}
		$('#bigModal').show();
	},
    popUpMenus : function() {
		$('.popUpMenuClick').each(function() {
			var tipContentID = $(this).attr('content');
			var target = 'bottomMiddle';
			var tooltip = 'topMiddle';
			if ($(this).attr('target')) {
				target = $(this).attr('target');
			}
			if ($(this).attr('tooltip')) {
				tooltip = $(this).attr('tooltip');
			}
			if ($(this).attr('tooltip')) {
				tooltip = $(this).attr('tooltip');
			}

			$(this).click(function() {
				return false;
			});

			var corner = tooltip;
			var tipContent   = $('#'+tipContentID).html();
			if (tipContent == null) {
				tipContent = " ";
			}
			var elementID    = $(this).attr('id');
               $('#'+elementID).qtip({
                    content:    {
						text:      tipContent,
						prerender: true
					},
                    position: {
						corner: {
							   target:  target,
							   tooltip: tooltip
						   }
                    },
                    show: {
                       when: 'click',
                       delay: 0,
                       solo: true,
                       ready: false
                    },
                    hide: {
                       when: {
                           event: 'unfocus'
                       }
                    },
                    style: {
                       border: {
                           width: 5
                       },
                       tip: {
                           corner: corner
                       },
                       name: 'cream',
                       width: 300,
                       padding: 6
                    }
               });
        });

	$('.settingsField').each(function() {
		var settingType  = $(this).attr('settingType');
		var fieldID      = $(this).attr('id');
		var position     = $(this).attr('position');

		var target  = 'bottomLeft';
		var tooltip = 'topLeft';

		if (position == 'top') {
		    target  = 'topLeft';
		    tooltip = 'bottomLeft';
		}

		$(this).qtip({
		     content:    {
			prerender: true,
			text: '<a href="#" settingType="'+settingType+'" fieldID="'+fieldID+'" class="settingsLink icon_settings_small">Edit settings</a>'
		     },
		     position: {
			 corner: { target:  target, tooltip: tooltip }
		     },
		     hide: {
			    fixed: true,
			    when: {
				    target: $(this),
                    event: 'blur'
                    },
				effect: {
					type: 'fade',
					length: '1000'
				}
			 },
			 show: {
				when: {
		   target: $(this),
		   event: 'focus'
	       }
			 },
			 style: {
				padding: 1,
				name: 'cream'
			 }
		});
	});
    },
    feedPopups : function() {
        $('.linkFeed').each(function() {	
			$(this).click(function() {
				return false;
			});

            var tipContent;
            var feedType = $(this).attr('type');
            var feedLink = $(this).attr('href');
            var feedTitle = $(this).html();
            if (feedType == 'rss') {
                tipContent  = '<span class="icon_rss_small" style="margin-bottom: 6px;">'+feedTitle+'</span>';
                tipContent += commonTerms['rssFeedText'];
            } else if (feedType == 'ical') {
                tipContent  = '<span class="icon_ical_small" style="margin-bottom: 6px;">'+feedTitle+'</span>';
                tipContent += commonTerms['icalFeedText'];
            }
            tipContent += '<div style="margin-top: 6px;"><a href="'+feedLink+'">'+feedLink+'</a></div>';
			
            $(this).qtip({
                content: { text: tipContent, prerender: true },
                position: {
                    corner: {
                           target:  'topLeft',
                           tooltip: 'bottomRight'
                       }
                },
                show: {
                   when: 'click',
                   delay: 0,
                   solo: true,
                   ready: false
                },
                hide: {
                   when: {
                       event: 'unfocus'
                   }
                },
                style: {
                   tip: {
                       corner: 'rightBottom'
                   },
                   border: {
                       width: 5
                   },
                   name: 'cream',
                   width: 500,
                   padding: 6
                }
           });
        });
    }
}

var bugReportObj = {
    attachEventHandlers : function() {
        $('.buttonSubmitBugReport').click(function() {
           bugReportObj.saveBugReport($(this));
           $(this).prev().val('');
           $(this).next().show().fadeOut(4000);
        });
    },
    saveBugReport : function(button) {
        var bugContent = button.prev().val();
        var formHash = {
                bugContent  : bugContent,
                thisPage    : thisPage
            }

        $.ajax({
            type:  "POST",
            url:   siteURL+'bugs/Bugs/saveBugReport',
            data: formHash,
            success: function(){
                
            },
            error: function (xhr, desc, exceptionobj) {
                errorObj.ajaxError(xhr,desc,exceptionobj);
            }
        });
    }
}

var settingsObj = {
	settingLinkInit : function() {
		$('.settingsLink').click(function() {
			var settingType  = $(this).attr('settingType');
			var fieldID      = $(this).attr('fieldID');
			var settingValue = $('#'+fieldID).val();

			var formHash = {
                    settingType  : settingType,
                    settingValue : settingValue
			}

			$.ajax({
				type:  "POST",
				url:   siteURL+'settings/SettingsOwners/saveSettings',
				data: formHash,
				dataType: 'json',
				success: function(payload){
					
				},
				error: function (xhr, desc, exceptionobj) {
					errorObj.ajaxError(xhr,desc,exceptionobj);
				}
			});

			$('#'+fieldID).addClass('savedField');
            return false;
		});
	},
    putSettingValuesInForm : function() {
        var settingsObj = eval(settingsJSON);
        for(var a in settingsObj) {
            var fieldID = settingsObj[a].Setting;
            var fieldValue = settingsObj[a].SettingValue;
            /*
             * See if we're dealing with a radio or checkbox field
             */
            var fieldArray = fieldValue.split('_');
            if (fieldArray[1] == 'radio') {
                $('#'+fieldID).attr('checked',true);
            } else if (fieldArray[1] == 'checkbox') {
                $('#'+fieldID).attr('checked',true);
            } else {
                $('#'+fieldID).val(fieldValue);
            }
        }
    }
}

var helpObj = {
	contextHelp : function() {
		$('.help').each(function() {
			var helpID = $(this).attr('id');
            var helpIDArray = helpID.split('_');
            if (helpIDArray[0] == 'trigger') {
				var helpIDContent = helpIDArray[1];
            } else {
				var helpIDContent = helpID;
            }
            var tipContent = $('#help_'+helpIDContent).html();

			var target = 'rightMiddle';
			var tooltip = 'leftMiddle';
			if ($(this).attr('target')) {
				target = $(this).attr('target');
			}
			if ($(this).attr('tooltip')) {
				tooltip = $(this).attr('tooltip');
			}
			if ($(this).attr('tooltip')) {
				tooltip = $(this).attr('tooltip');
			}
			var corner = tooltip;

		    $(this).qtip({
				content: tipContent,
				position: {
				corner: {
					   target:  target,
					   tooltip: tooltip
				   }
				},
				show: {
				   when: {
					 event: 'mouseover'
				   },
				   delay: 0
				},
				hide: {
				   when: {
					   event: 'mouseout'
				   },
				   effect: {
					   type: 'fade'
				   }
				},
				style: {
				   tip: {
					   corner: corner
				   },
				   name: 'cream',
				   width: 250,
				   padding: 12
				}
		   });
		});
	}
}

var statusObj = {
	statusPopup : function() {
		$('.status').each(function() {
            var tipContent = $(this).data('statusText');

			var target = 'rightMiddle';
			var tooltip = 'leftMiddle';
			if ($(this).attr('target')) {
				target = $(this).attr('target');
			}
			if ($(this).attr('tooltip')) {
				tooltip = $(this).attr('tooltip');
			}
			if ($(this).attr('tooltip')) {
				tooltip = $(this).attr('tooltip');
			}
			var corner = tooltip;

		    $(this).qtip({
				content: tipContent,
				position: {
					corner: {
						   target:  target,
						   tooltip: tooltip
					   }
				},
				show: {
				   when: 'mouseover',
				   delay: 0,
				   solo: true
				},
				hide: {
				   when: {
					   target: $(this),
					   event: 'mouseout'
				   },
				   effect: {
					   type: 'fade'
				   }
				},
				style: {
				   tip: {
					   corner: corner
				   },
				   name: 'cream',
				   width: 200,
				   padding: 3
				}
		   });
		});
	},
    getStatusBackground : function(statusClass) {
        var statusColorClass = '';
        switch(statusClass) {
            case 'status_past_due':
                statusColorClass = 'light-red';
                break;
            case 'status_completed':
                statusColorClass = 'light-green';
                break;
            case 'status_on_hold':
                statusColorClass = 'gold';
                break;
            case 'status_not_started':
                statusColorClass = 'light-gray';
                break;
            case 'status_in_progress':
                statusColorClass = 'light-blue';
                break;
            default:
                statusColorClass = 'light-gray';
        }
        return statusColorClass;
    }
}

var printObj = {
    initPrint : function() {
        if ($('.buttonPrint').length>0) {
	        $('.buttonPrint').click(function() {
	               var itemID    = $(this).attr('itemID');
	               var printWhat = $(this).attr('printWhat');
	               printObj.goPrint(itemID, printWhat);
	               return false;
	        });
        }
    },
	goPrint : function(itemIDString,printWhat) {
		var frameURL = siteURL+'print/PrintPDF/print'+printWhat+'/'+itemIDString;
        //alert(frameURL);
	    $('#printFrame').attr('src',frameURL);
	}
}

var exportObj = {
    exportExcel : function(itemIDString,exportWhat,exportFormat) {
		var frameURL = siteURL+'export/'+exportFormat+'/export'+exportWhat+'/'+itemIDString;
		$('#exportFrame').attr('src',frameURL);
	},
    exportAccountData : function() {
		var frameURL = siteURL+'export/ExportAccountData/';
		$('#exportFrame').attr('src',frameURL);
	}
}

var errorObj = {
	ajaxError : function(xhr,desc,exceptionobj) {
		//console.log('AJAX Error');
	}
}

var formObj = {
	initForm : function() {
		/*
		 * Look for fields that need to be cleared on focus
		 */
		$('.clearOnFocus').focus(function() {
			$(this).val('').removeClass('clearOnFocus');
			return false;
		});
	}	
}	

var teamMemberObj = {
    createTeamCheckboxes : function(orientation,className,appendTo,tabIndex) {
        if (className == '') {
            className = 'chkTeamMember';
        }
        if (tabIndex == '') {
            tabIndex = 1;
        }

        var teamMemberArray = eval(teamMembers);
		if (teamMemberArray.length>0) {
            var memberString = '<ul id="teamMemberList" class="noBullet '+orientation+'">';

            for(var a=0;a<=((teamMemberArray.length)-1);a++) {
                var checkedStatus = '', hiliteStatus = '';
                /*
                 * If team member is logged user, check by default
                 */
                if (teamMemberArray[a].UID == numbers[0]) {
                    checkedStatus = 'checked';
                    hiliteStatus = 'elementHilite';
                }
                memberString += '<li class="'+hiliteStatus+'"><input type="checkbox" value="'+teamMemberArray[a].UID+'" tabindex="'+tabIndex+'" language="'+teamMemberArray[a].Language+'" class="'+className+'" '+checkedStatus+' /> <a href="#" class="'+className+'Link">'+teamMemberArray[a].First_Name+' '+teamMemberArray[a].Last_Name+'</a></li>';
                tabIndex++;
            }

            memberString += '</ul>';

            if (appendTo != '') {
                $('#'+appendTo).append(memberString);
                
                $('.'+className)
                    .bind('keydown', function(e) {
                        e.stopPropagation();
                        if (e.keyCode == 13) {
                            if ($(this).is(':checked')) {
                                 $(this).removeAttr('checked');
                                 $(this).parent().removeClass('elementHilite');
                            } else {
                                $(this).attr('checked','checked');
                                $(this).parent().addClass('elementHilite');
                            }
                            return false;
                        }
                  })
                    .focus(function() {
                        $(this).parent().addClass('elementHilite');
                    })
                    .blur(function() {
                        $(this).parent().removeClass('elementHilite');
                    });

                $('.'+className+'Link').click(function() {
                    if ($(this).prev().is(':checked')) {
                         $(this).prev().removeAttr('checked');
                         $(this).parent().removeClass('elementHilite');
                    } else {
                        $(this).prev().attr('checked','checked');
                        $(this).parent().addClass('elementHilite');
                    }
                    return false;
                });
            } else {
                return memberString;
            }
		} else {
			return false;
		}
    }
}

var googleMapObj = {
	showGoogleMap : function (address, mapDiv, pointerText) {
		var map = new GMap2(document.getElementById(mapDiv));
		var geocoder = new GClientGeocoder();
		geocoder.getLatLng(address, function(point){
			if (!point) {
				//alert(address + " not found");
                $('#'+mapDiv).hide();
			} else {
				map.setCenter(point, 13);
				map.addControl(new GSmallMapControl());
				var marker = new GMarker(point);
				map.addOverlay(marker);
				marker.openInfoWindowHtml(pointerText);
			}
		});	
	}
}

var languageObj = {
    initLanguageSelect : function() {
        $('.languageSelect').click(function() {
            var id = $(this).attr('id');
            var idArray  = id.split('_');
            var langCode = idArray[1];

            $.get(siteURL+'settings/SettingsOwners/changeLanguage/'+langCode, function() {
                window.location.reload(true);
            });

            return false;
        });
    }
}

var filesObj = {	
    attachUploadEventHandlers : function() {
        $('.lnkOpenFileUpload').click(function() {
           $('#fileListContainer').toggle(false);
           $('#fileUploaderContainer').toggle(true);
           $.get(siteURL+'files/FileManager/setNodeIDInSession/'+fileManagerNodeID);
           filesObj.initPlupload();
        });        
    },
    initPlupload : function() {
        //runtimes : pluploadRuntimes,
        $(".fileUploaderContainer").pluploadQueue({
            runtimes : pluploadRuntimes,
            url : siteURL+'files/FileManager/uploadFileHandler',
            max_file_size : '500MB',
            unique_names : false,
            flash_swf_url : flashDir+'plupload.flash.swf',
            silverlight_xap_url : flashDir+'plupload.silverlight.xap',
            preinit : function(up) {
               up.bind('Init', function() {
                  $('.plupload_close').click(function() {
                        $('#fileUploaderContainer').toggle(false);
                        $('#fileListContainer').toggle(true);

                        if ($('#pageLeftColumn').attr('pageID') == 'fileView') {
                            $('#panelUpload').toggle(false);
                            $('#panelDefault').toggle(true);
                            $('#panelNewFolder').toggle(false);
                        }
                       
                        return false;
                    });
               });
            }
        });

        var uploader = $(".fileUploaderContainer").pluploadQueue();
        uploader.bind('FileUploaded', function(up, file, response) {
            fileManagerObj.uploadFileSuccess(response.response);
            if (up.total.queued == 0) {
                filesObj.initPlupload();
            }    
        });
    },
    getFileTypeFromClassName : function(obj) {
        if (obj.hasClass('icon_file_doc')) {
            return 'application/msword';
        } else if (obj.hasClass('icon_file_xls')) {
            return 'application/excel';
        } else if (obj.hasClass('icon_file_pdf')) {
            return 'application/pdf';
        } else if (obj.hasClass('icon_file_ppt')) {
            return 'application/powerpoint';
        } else {
            return 'application/octet-stream';
        }
    }
}

var sortObj = {
        sortByCompanyAsc : function(a,b) {
            if (a.Company != null) {
                var x = a.Company.toLowerCase();
            }
            if (b.Company != null) {
                var y = b.Company.toLowerCase();
            }
            return ((x < y) ? -1 : ((x > y) ? 1 : 0));
        },      
        sortByCompanyDesc : function(a, b) {
            if (a.Company != null) {
                var x = a.Company.toLowerCase();
            }
            if (b.Company != null) {
                var y = b.Company.toLowerCase();
            }
            return ((x < y) ? 1 : ((x > y) ? -1 : 0));
        },        
        sortByProjectNumberAsc : function(a, b) {
            var x = a.TotalProjects;
            var y = b.TotalProjects;
            return ((x < y) ? -1 : ((x > y) ? 1 : 0));
        },      
        sortByProjectNumberDesc : function(a, b) {
            var x = a.TotalProjects;
            var y = b.TotalProjects;        
            return ((x < y) ? 1 : ((x > y) ? -1 : 0));
        },
        sortByStatusAsc : function(a, b) {
            var x = a.Status;
            var y = b.Status;
            return ((x < y) ? -1 : ((x > y) ? 1 : 0));
        },
        sortByStatusDesc : function(a, b) {
            var x = a.Status;
            var y = b.Status;
            return ((x < y) ? 1 : ((x > y) ? -1 : 0));
        },
        sortByTitleAsc : function(a, b) {
            var x = a.Title.toLowerCase();
            var y = b.Title.toLowerCase();
            return ((x < y) ? -1 : ((x > y) ? 1 : 0));
        },
        sortByTitleDesc : function(a, b) {
            var x = a.Title.toLowerCase();
            var y = b.Title.toLowerCase();
            return ((x < y) ? 1 : ((x > y) ? -1 : 0));
        },
        sortByProjectHoursAsc : function(a, b) {
            var x = a.ProjectTime;
            var y = b.ProjectTime;
            
            var x = parseFloat(x);
            var y = parseFloat(y);
            return ((x < y) ? -1 : ((x > y) ? 1 : 0));
        },      
        sortByProjectHoursDesc : function(a, b) {
            var x = a.ProjectTime;
            var y = b.ProjectTime;
            
             var x = parseFloat(x);
             var y = parseFloat(y);
            return ((x < y) ? 1 : ((x > y) ? -1 : 0));
        },
        sortByProjectDateEndAsc : function(a, b) {
                
        },
        sortByProjectDateEndDesc : function(a, b) {
                
        },
        sortByInvoiceAmountAsc : function(a, b) {
                var x = a.InvoiceTotal;
            var y = b.InvoiceTotal;

            var x = parseFloat(x);
            var y = parseFloat(y);
            return ((x < y) ? -1 : ((x > y) ? 1 : 0));
        },
        sortByInvoiceAmountDesc : function(a, b) {
            var x = a.InvoiceTotal;
            var y = b.InvoiceTotal;

             var x = parseFloat(x);
             var y = parseFloat(y);
            return ((x < y) ? 1 : ((x > y) ? -1 : 0));
        },
        sortByTaskNumberAsc : function(a, b) {
            var x = a.TaskNo;
            var y = b.TaskNo;
            return ((x < y) ? -1 : ((x > y) ? 1 : 0));
        },
        sortByTaskNumberDesc : function(a, b) {
            var x = a.TaskNo;
            var y = b.TaskNo;
            return ((x < y) ? 1 : ((x > y) ? -1 : 0));
        }
}

var chartInitObj = {
    initOpenFlashChart : function(width,height,defaultDataFile,chartContainer) {
        if (chartContainer == '') {
            chartContainer = 'chartContainer';
        }
        var flashvars = {};
        var attributes = {};
        var params = {
            wmode: 'transparent'
        };
        swfobject.embedSWF(
            flashDir+'open-flash-chart.swf',
            chartContainer,
            width,height,'9.0.0',
            flashDir+'expressInstall.swf',
            {
                'data-file' : defaultDataFile,
                'loading'   : commonTerms['loading']
            },
            params,attributes
        );
    }
}

var contactObj = {
    makeContactAutoSuggest : function(element,clients,contacts,team,vendors,cardView,attachToType,attachToID,boxWidth) {
        if (!boxWidth) {
            boxWidth = 400;
        }
        if (clients == true) {
            clients = 1;
        } else {
            clients = 0;
        }
        if (contacts == true) {
            contacts = 1;
        } else {
            contacts = 0;
        }
        if (team == true) {
            team = 1;
        } else {
            team = 0;
        }
        if (vendors == true) {
            vendors = 1;
        } else {
            vendors = 0;
        }
        element.autocomplete(siteURL+'contacts/AppContacts/searchContacts', {
			width:          boxWidth,
			highlight:      false,
			minChars:       3,
			scroll:         true,
			scrollHeight:   300,
			loadingClass:   'formFieldWait',
            extraParams:    {
                            clients : clients,
                            contacts: contacts,
                            team    : team,
                            vendors : vendors
                            }
		});

		element.result(function(event, data, formatted) {
			var contact         = data[0];
			var contactID       = data[1];
            var contactType     = data[5];
            var contactName     = data[3];
            var contactLanguage = data[4];

            var attrString;
            if (contactType == 'client') {
                attrString = 'class="clientLink" clientID="'+contactID+'"';
            } else {
                attrString = 'class="personLink" personID="'+contactID+'"';
            }

            if (attachToID>0) {
                element.val('');
                $.ajax({
                    type:  "POST",
                    url:   siteURL+'contacts/AppContacts/associatePersonWithItem/'+contactID+'/'+attachToID+'/'+attachToType,
                    success: function(payload){
                        if (cardView == true) {
                            getContactObj.getContacts(attachToType,attachToID,0,0);
                        } else {
                            var contactHTML = contactObj.renderContactListItem(contactID,contactType,contactLanguage,contactName,attrString);
                            element.next().append(contactHTML);
                        }
                    },
                    error: function (xhr, desc, exceptionobj) {
                        errorObj.ajaxError(xhr,desc,exceptionobj);
                    }
                });
                /*
                if (cardView == true) {
                    getContactObj.getContacts(attachToType,attachToID,0,0);
                } else {
                    var contactHTML = contactObj.renderContactListItem(contactID,contactType,contactLanguage,contactName,attrString);
                    element.next().append(contactHTML);
                }
                */
            } else {
                element.val('');
                var contactHTML = contactObj.renderContactListItem(contactID,contactType,contactLanguage,contactName,attrString);
                element.next().append(contactHTML);
            }

            $('.removeContact').unbind('click').click(function() {
                $(this).parent().remove();
                return false;
            });

            //contactObj.makeContactLinks();
		});
    },
    renderContactListItem : function(contactID,contactType,contactLanguage,contactName,contactAttrString) {
        var contactHTML  = '<p class="messageRecipientContainer recipSelected noBorder">';
            contactHTML += '<input class="recipData" type="hidden" value="'+contactID+'" recipType="'+contactType+'" recipLanguage="'+contactLanguage+'" />';
            contactHTML += '<a href="#" class="buttonDeleteSmall removeContact" title="'+commonTerms['remove']+'"></a>';
            contactHTML += '<a href="#" '+contactAttrString+'>'+contactName+'</a></p>';
        return contactHTML;
    },
    makeContactLinks : function() {
        $('body').delegate('.personLink', 'click', function(event) {
            var personID = $(this).attr('personID');
            $(this).qtip({
               overwrite: false,
               content: {
                   url: siteURL+'contacts/AppContacts/getContact/'+personID+'/html/0',
                   method: 'GET'
               },
               position: {
					corner: {
						   target:  'rightMiddle',
						   tooltip: 'leftMiddle'
					   }
				},
                show: {
				   event: event.type,
				   delay: 0,
                   solo: true,
                   ready: true
				},
				hide: {
				   when: {
					   event: 'unfocus'
				   },
				   effect: {
					   type: 'fade'
				   }
				},
				style: {
				   tip: {
					   corner: 'leftMiddle'
				   },
				   name: 'cream',
				   width: 300,
				   padding: 3
				}
            }, event);
            return false;
        });

        $('body').delegate('.clientLink', 'click', function(event) {
            var clientID = $(this).attr('clientID');
            $(this).qtip({
               overwrite: false,
               content: {
                   url: siteURL+'clients/ClientView/getClient/'+clientID+'/html/0',
                   method: 'GET'
               },
               position: {
					corner: {
						   target:  'rightMiddle',
						   tooltip: 'leftMiddle'
					   }
				},
                show: {
				   event: event.type,
				   delay: 0,
                   solo: true,
                   ready: true
				},
				hide: {
				   when: {
					   event: 'unfocus'
				   },
				   effect: {
					   type: 'fade'
				   }
				},
				style: {
				   tip: {
					   corner: 'leftMiddle'
				   },
				   name: 'cream',
				   width: 300,
				   padding: 3
				}
            }, event);
            return false;
        });
    }
}

var permissionsObj = {
    renderControlsBasedOnPermissions : function() {
        for (var key in permJSON) {
            if (permJSON.hasOwnProperty(key)) {
                if (permJSON[key] == '1') {
                    $('.'+key).show();
                } else {
                    $('.'+key).hide();
                }
            }

            /*
             * Look for exceptions that don't match the simple rule above
             */
            if (permJSON['taskViewAll'] == '1' || permJSON['taskViewOwn'] == '1') {
                $('.taskView').show();
            } else {
                $('.taskView').hide();
            }

            if (permJSON['invoiceViewAll'] == 1 || permJSON['invoiceViewOwn'] == 1) {
                $('.invoiceViewAll').show();
            } else {
                $('.invoiceViewAll').hide();
            }

            if (permJSON['invoiceCreateSend'] == 1 || permJSON['invoiceCreateSendToAccountOwner'] == 1) {
                $('.invoiceCreateSend').show();
            } else {
                $('.invoiceCreateSend').hide();
            }

            if (permJSON['timesheetViewAll'] == 1 || permJSON['timesheetViewOwn'] == 1) {
                $('.timesheetViewAll').show();
            } else {
                $('.timesheetViewAll').hide();
            }

            if (permJSON['teamCreate'] == 1) {
                $('.teamCreate').show();
            } else {
                $('.teamCreate').hide();
            }

            if (permJSON['calendarCreate'] == 1) {
                $('.calendarCreate').show();
            } else {
                $('.calendarCreate').hide();
            }
        }
    }
}

var siteSearchObj = {
    initSearchBox : function() {
        var clientID = 0;
        if ($('#clientArea').val() == 1) {
            clientID = $('#clientID').val();
        }

        $("#appSearch").autocomplete(siteURL+'search/SiteSearch/siteSearchAutocomplete/'+clientID, {
			width:          300,
			highlight:      false,
			minChars:       3,
			scroll:         true,
			scrollHeight:   300,
			loadingClass:   'formFieldWait',
            selectFirst:    false
		});
        
		$("#appSearch").result(function(event, data, formatted) {
			var searchItemIDString = data[1];
			var searchItemIDArray = searchItemIDString.split('_');
			var group  = searchItemIDArray[0];
			var itemID = searchItemIDArray[1];
			$("#appSearch").val('');

            var link;
            switch (group) {
                case 'invoice':
                    link = siteURL+'finances/FinanceView/viewInvoice/'+itemID;
                    break;
                case 'project':
                    link = siteURL+'projects/ProjectDetail/index/'+itemID;
                    break;
                case 'expense':
                    link = siteURL+'finances/FinanceView/viewExpense/'+itemID;
                    break;
                case 'client':
                    link = siteURL+'clients/ClientDetail/index/'+itemID;
                    break;
                case 'event':
                    link = siteURL+'calendar/CalendarView/viewEvent/'+itemID;
                    break;
            }
            window.location = link;
		});
        

        $('#buttonAppSearch').click(function() {
            $('#formSiteSearch').submit();
        });
    }
}

var genericFunctions = {
    isFileAnImage : function(fileExt) {
        var isImage = false;
        if (fileExt == 'jpg' || fileExt == 'jpeg' || fileExt == 'gif' || fileExt == 'png' || fileExt == 'bmp' || fileExt == 'tiff') {
            isImage = true;
        }
        return isImage;
    },
	checkMouseBoundary : function(click, boundary) {
	    var element = $(click.target);
	    var boundary = $(boundary);

	    while(true)
	    {
	        if(element == boundary)
	        {
	            return alert('I am inside the boundary ...');
	        }
	        else if(element == document)
	        {
	            return alert('I am outside the boundary ...');
	        }
	        else
	        {
	            element = $(element).parent();
	        }
	    }
	
	    return true;
	},
	jsToMySQLDate : function(jsDate) {
		var dateArray = jsDate.split('/');
		var newDate = dateArray[2]+'-'+dateArray[0]+'-'+dateArray[1];
		return newDate;
	},
    checkboxTrigger : function() {
        $('body').delegate('.checkboxTrigger', 'click', function() {
           var checkbox = $(this).prev();
           if (checkbox.attr('checked') == true) {
               checkbox.attr('checked',false);
           } else {
               checkbox.attr('checked',true);
           }
        });
    },
    togglePageHeaderButtons : function(buttonSelector,newState) {
        /*
         * Determing current state
         */
        var currentState = 'off';
        if ($(buttonSelector).is(':visible')) {
            currentState = 'on';
        }
        if (newState != currentState) {
            /*
             * Then we need to toggle
             */
             if (currentState == 'off') {
                 $(buttonSelector).show();
             } else  {
                 $(buttonSelector).hide();
             }
        }
    },
	replaceURLWithHyperlink : function(string) {
		string = string.replace(/((ftp|https?):\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?)/gm,'<a href="$1" target="_blank">$1</a>');
		return string;
	},
	twitterReplaceMention : function(string) {
		string = string.replace(/([^\w])\@([\w\-]+)/gm,'$1@<a href="http://twitter.com/$2" target="_blank">$2</a>');
		return string;
	},
	twitterReplaceHashtags : function(string) {
		string = string.replace(/([^\w])\#([\w\-]+)/gm,'$1<a href="http://twitter.com/search?q=%23$2" target="_blank">#$2</a>');
		return string;
	},
    txtToField : function(string) {
        /*
         * Replace <br>, <br />
         */
        var newString  = string.replace(/<br>/g,"\r\n");
        newString = newString.replace(/<br\/>/g,"\r\n");

        /*
         * Replace ' and " html codes with actual characters
         */
        newString = newString.replace(/&#39;/g,"'");
        newString = newString.replace(/&#34;/g,'"');
        newString = newString.replace(/&quot;/g,'"');
        newString = newString.replace(/&amp;/g,'&');
        
        /*
         * Remove any other HTML tags like links
         */
        newString = newString.stripTags();
        return newString;
    },
    togglePanel : function(panelObject) {
        if (panelObject.is(':visible')) {
            panelObject.slideUp('fast');
            return 'closed';
        } else {
            panelObject.slideDown('fast');
            return 'open';
        }
    },
    prepTogglePanels : function() {
        $('.rollPanelTrigger').click(function() {
           var targetPanel = $(this).next();
           genericFunctions.togglePanel(targetPanel);
           return false;
        });
    }
}

String.prototype.replaceAll = function(strTarget,strSubString) {
	var strText = this;
	var intIndexOfMatch = strText.indexOf( strTarget );
		  
	// Keep looping while an instance of the target string
	// still exists in the string.
	while (intIndexOfMatch != -1){
		// Relace out the current instance.
		strText = strText.replace( strTarget, strSubString )
		 
		// Get the index of any next matching substring.
		intIndexOfMatch = strText.indexOf( strTarget );
	}
	  
	// Return the updated string with ALL the target strings
	// replaced out with the new substring.
	return( strText );
}
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}
String.prototype.stripTags = function () {
   return this.replace(/<([^>]+)>/g,'');
}
String.prototype.stripAnchor = function () {
    var rx = new RegExp("<a .*?>(.*?)</a>","i");
    return this.replace(rx,"$1");
}

function ofc_ready() {}

function open_flash_chart_data() {}

function findSWF(movieName) {
    if (navigator.appName.indexOf("Microsoft")!= -1) {
        return window[movieName];
    } else {
        return document[movieName];
    }
}

$(document).ready(function() {
	if (logged == 1) {
		pageInitObj.initPage();
	}
});	
